#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>


class Sock
{
public:
    static int Socket()
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock < 0)
        {
            std::cerr << "socket failed" << std::endl;
            exit(1);
        }
    }

    static void Bind(int sock, uint16_t port)
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        
        if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            std::cerr << "bind failed" << std::endl;
            exit(2);
        }
    }

    static void Listen(int sock)
    {
        const int backlog = 5;
        if(listen(sock, backlog) < 0)
        {
            std::cerr << "listen failed" << std::endl;
            exit(3);
        }
    }

    // tcp通信直接在套接字中写就可以，所以可以不用返回客户端的信息
    static int Accept(int sock)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        
        int new_sock = accept(sock, (struct sockaddr*)&peer, &len);
        if(new_sock < 0)
        {
            std::cerr << "accept failed" << std::endl;
            exit(4);
        }

        return new_sock;
    }

    static void Connect(int sock, const std::string& ip, uint16_t port)
    {
        struct sockaddr_in server;
        memset((void*)&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = inet_addr(ip.c_str());

        if(connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
        {
            std::cerr << "connect failed" << std::endl;
            exit(5);
        }
        else
        {
            std::cout << "connect succeed" << std::endl;
        }
    }
};